package com.yunsc.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunsc.common.exception.BizCodeEnum;
import com.yunsc.common.exception.YunscException;
import com.yunsc.common.utils.PageResult;
import com.yunsc.media.entity.YunscUploadFileEntity;
import com.yunsc.media.service.YunscUploadFileService;
import com.yunsc.product.dao.YunscGoodsCategoryDao;
import com.yunsc.product.dao.YunscGoodsCategoryRelDao;
import com.yunsc.product.dao.YunscGoodsDao;
import com.yunsc.product.dao.YunscGoodsImageDao;
import com.yunsc.product.dto.*;
import com.yunsc.product.entity.*;
import com.yunsc.product.service.*;
import com.yunsc.product.vo.GoodsDetailVO;
import com.yunsc.product.vo.GoodsInfoVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service("yunscGoodsService")
public class YunscGoodsServiceImpl extends ServiceImpl<YunscGoodsDao, YunscGoodsEntity> implements YunscGoodsService {

    @Resource
    private YunscGoodsCategoryRelDao goodsCategoryRelDao;
    @Resource
    private YunscGoodsImageDao goodsImageDao;
    @Resource
    private YunscUploadFileService uploadFileService;
    @Resource
    private YunscSpecService specService;
    @Resource
    private YunscGoodsSpecRelService goodsSpecRelService;
    @Resource
    private YunscSpecValueService specValueService;
    @Resource
    private YunscGoodsServiceImpl goodsService;
    @Resource
    private YunscGoodsSkuService goodsSkuService;
    @Resource
    private YunscGoodsCategoryRelService goodsCategoryRelService;
    @Resource
    private YunscGoodsImageService goodsImageService;
    @Resource
    private YunscGoodsServiceRelService goodsServiceRelService;
    @Resource
    private YunscGoodsCategoryDao goodsCategoryDao;


    @Override
    public PageResult<GoodsInfoVO> queryGoodsList(QueryGoodsDTO params, Integer currentStoreId) {
        Page<GoodsInfoVO> page = new Page<>(params.getPage(), params.getPageSize());
        IPage<GoodsInfoVO> goodsListVoIPage = this.baseMapper.selectGoodsPageList(page, params, currentStoreId);
        List<GoodsInfoVO> records = goodsListVoIPage.getRecords();
        // 设置商品图片
        records.forEach(goods -> goods.setGoodsImage(goodsService.queryGoodsDefaultImageUrl(goods.getGoodsId())));
        // 设置商品排序
        String sortType = params.getSortType();
        if (sortType != null && sortType.equals("price")) {
            if (params.getSortPrice() == 1) {
                records.sort(Comparator.comparing(GoodsInfoVO::getGoodsPriceMin).reversed());
            } else {
                records.sort(Comparator.comparing(GoodsInfoVO::getGoodsPriceMin));
            }
        } else if (sortType != null && sortType.equals("sales")) {
            records.sort(Comparator.comparing(GoodsInfoVO::getGoodsSales).reversed());
        }
        return PageResult.formatPageResult(records, params.getPage(), params.getPageSize(), goodsListVoIPage.getTotal());
    }

    // 查询分类下的商品列表
    @Override
    public PageResult<GoodsInfoVO> queryShopGoodsList(QueryGoodsDTO params, Integer currentStoreId) {
        Integer categoryId = params.getCategoryId();
        if (categoryId != null && categoryId > 0){
            // 查询分类下的所有子分类
            List<Integer> categoryIds = goodsCategoryDao.selectChildCategoryIds(categoryId);
            if (CollectionUtils.isEmpty(categoryIds)){
                params.setCategoryIds(Collections.singletonList(categoryId));
            }else{
                params.setCategoryIds(categoryIds);
            }
        }
        Page<GoodsInfoVO> page = new Page<>(params.getPage(), params.getPageSize());
        IPage<GoodsInfoVO> goodsListVoIPage = this.baseMapper.selectGoodsList(page, params, currentStoreId);
        List<GoodsInfoVO> records = goodsListVoIPage.getRecords();
        // 设置商品图片
        records.forEach(goods -> goods.setGoodsImage(goodsService.queryGoodsDefaultImageUrl(goods.getGoodsId())));
        // 设置商品排序
        String sortType = params.getSortType();
        if (sortType != null && sortType.equals("price")) {
            if (params.getSortPrice() == 1) {
                records.sort(Comparator.comparing(GoodsInfoVO::getGoodsPriceMin).reversed());
            } else {
                records.sort(Comparator.comparing(GoodsInfoVO::getGoodsPriceMin));
            }
        } else if (sortType != null && sortType.equals("sales")) {
            records.sort(Comparator.comparing(GoodsInfoVO::getGoodsSales).reversed());
        }
        return PageResult.formatPageResult(records, params.getPage(), params.getPageSize(), goodsListVoIPage.getTotal());
    }


    @Override
    public GoodsDetailVO queryGoodsDetailById(Integer goodsId) {
        GoodsBaseDTO goods = this.baseMapper.selectGoodsBaseById(goodsId);
        if (goods == null) {
            return null;
        }
        // 设置商品分类
        List<Integer> categoryIds = goodsCategoryRelDao.queryCategoryIdsByGoodsId(goodsId);
        goods.setCategoryIds(categoryIds);

        GoodsDetailVO goodsDetail = new GoodsDetailVO();
        BeanUtils.copyProperties(goods, goodsDetail);
        // 格式化商品content
        String content = goods.getContent();
        String content_new = content.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"");
        goodsDetail.setContent(content_new);
        // 设置商品折扣
        String aloneGradeEquity = (String) goods.getAloneGradeEquity();
        if (!StringUtils.isEmpty(aloneGradeEquity) && !aloneGradeEquity.equals("[]")) {
            // 将JSON字符串转换为Map对象
            Map<String, Object> map = JSON.parseObject(aloneGradeEquity, new TypeReference<Map<String, Object>>() {
            });
            goodsDetail.setAloneGradeEquity(map);
        }
        // 商品销量
        goodsDetail.setGoodsSales(goods.getSalesInitial() + goods.getSalesActual());
        // 商品图片
        List<Integer> imageIds = goods.getImagesIds();
        if (imageIds != null) {
            // 设置商品图片集合
            List<YunscUploadFileEntity> imageList = uploadFileService.queryFilesByIds(imageIds);
            // 设置商品主图
            if (imageList != null && imageList.size() > 0) {
                goodsDetail.setGoodsImage(imageList.get(0).getExternalUrl());
                goodsDetail.setGoodsImages(imageList);
            }else{
                goodsDetail.setGoodsImages(Collections.emptyList());
            }
        }
        // 商品分类
        goodsDetail.setCategoryIds(goods.getCategoryIds());
        // 商品规格
        List<SpecListDTO> specList = goodsSpecRelService.querySpecListById(goodsId);
        goodsDetail.setSpecList(specList);
        // 商品服务ids
        goodsDetail.setServiceIds(goods.getServiceIds());
        // goodsDetail.setIsSpecLocked(false);
        // 商品sku
        goodsDetail.setSkuList(goodsSkuService.querySkuListByGoodsId(goodsId));
        // 商品视频
        if (goods.getVideoId() != null) {
            goodsDetail.setVideo(uploadFileService.queryFileById(goodsDetail.getVideoId()));

        }
        // 商品视频封面
        if (goods.getVideoCoverId() != null) {
            goodsDetail.setVideoCover(uploadFileService.queryFileById(goodsDetail.getVideoCoverId()));
        }
        goodsDetail.setDeliveryType(JSON.parseObject(goods.getDeliveryType().toString(), List.class));

        return goodsDetail;
    }

    // 获取商品图片url
    @Override
    public String queryGoodsDefaultImageUrl(Integer goodsId) {
        List<Integer> imageIds = goodsImageDao.queryImageIdsByGoodsId(goodsId);
        if (imageIds == null) {
            return null;
        }
        YunscUploadFileEntity file = uploadFileService.queryFileById(imageIds.get(0));
        return file == null ? "" : file.getExternalUrl();
    }

    @Override
    public YunscUploadFileEntity queryGoodsDefaultImage(Integer goodsId) {
        List<Integer> imageIds = goodsImageDao.queryImageIdsByGoodsId(goodsId);
        if (imageIds == null) {
            return null;
        }
        return uploadFileService.queryFileById(imageIds.get(0));
    }

    @Override
    @Transactional
    public void saveGoodsInfo(GoodsBaseDTO goodsBase, Integer storeId) {
        goodsBase.setStoreId(storeId);
        // 1、添加数据到表goods
        Integer goodsId = goodsService.saveGoodsToDb(goodsBase, null);
        goodsBase.setGoodsId(goodsId);
        // 2、保存商品规格信息
        List<YunscSpecValueEntity> specValueList = goodsService.saveGoodsSpecToDb(goodsBase, goodsId);
        // 3、添加商品sku到表goods_sku
        goodsService.saveGoodsSkuToDb(goodsBase, specValueList);
        // 4、保存商品与分类关系记录表
        goodsService.saveGoodsCategoryToDb(goodsBase.getCategoryIds(), goodsId, storeId);
        // 5、保存商品与图片关系记录表
        goodsService.saveGoodsImageToDb(goodsBase.getImagesIds(), goodsId, storeId);
        // 6、保存商品与服务记录表
        goodsService.saveGoodsServiceToDb(goodsBase.getServiceIds(), goodsId, storeId);
    }

    // 保存商品基本信息
    @Override
    @Transactional
    public Integer saveGoodsToDb(GoodsBaseDTO goodsBase, String goodsId) {

        YunscGoodsEntity goodsEntity = new YunscGoodsEntity();
        BeanUtils.copyProperties(goodsBase, goodsEntity);
        SpecDataDTO specData = goodsBase.getSpecData();
        // 格式化商品content
        String content = goodsBase.getContent();
        String content_new = content.replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;");
        goodsEntity.setContent(content_new);
        // 商品配送方式(仅单独设置时有效)
        goodsEntity.setDeliveryType(JSON.toJSONString(goodsBase.getDeliveryType()));

        // 商品规格(10单规格 20多规格)
        if (goodsBase.getSpecType() == 10) {
            goodsEntity.setGoodsPriceMax(goodsBase.getGoodsPrice());
            goodsEntity.setGoodsPriceMin(goodsBase.getGoodsPrice());
            goodsEntity.setLinePriceMax(goodsBase.getGoodsPrice());
            goodsEntity.setLinePriceMin(goodsBase.getGoodsPrice());
            goodsEntity.setStockTotal(goodsBase.getStockNum());
        } else {
            List<SpecDataDTO.SkuList> skuList = specData.getSkuList();
            // 获取商品价格最大值
            OptionalDouble max = skuList.stream().mapToDouble(SpecDataDTO.SkuList::getGoodsPrice).max();
            if (max.isPresent()) {
                goodsEntity.setGoodsPriceMax(String.valueOf(max.getAsDouble()));
            }
            // 获取商品价格最小值
            OptionalDouble min = skuList.stream().mapToDouble(SpecDataDTO.SkuList::getGoodsPrice).min();
            if (min.isPresent()) {
                goodsEntity.setGoodsPriceMin(String.valueOf(max.getAsDouble()));
            }
            // 获取划线商品价格最大值
            OptionalDouble lineMax = skuList.stream().mapToDouble(SpecDataDTO.SkuList::getLinePrice).max();
            if (lineMax.isPresent()) {
                goodsEntity.setLinePriceMax(String.valueOf(lineMax.getAsDouble()));
            }
            // 获取划线商品价格最小值
            OptionalDouble lineMin = skuList.stream().mapToDouble(SpecDataDTO.SkuList::getLinePrice).min();
            if (lineMin.isPresent()) {
                goodsEntity.setLinePriceMin(String.valueOf(lineMin.getAsDouble()));
            }
            // 获取库存总数
            int sum = skuList.stream().mapToInt(SpecDataDTO.SkuList::getStockNum).sum();
            goodsEntity.setStockTotal(sum);
        }

        // 是否开启会员折扣（1开启0关闭）
        if (goodsBase.getIsEnableGrade() == 1) {
            // 是否是默认等级折扣
            if (goodsBase.getIsAloneGrade() == 0) {
                // 默认等级折扣
                goodsEntity.setAloneGradeEquity("[]");
            } else {
                // 单独设置折扣的配置
                Map<String, Object> aloneEquity = new HashMap<>();
                Object aloneGradeEquity = goodsBase.getAloneGradeEquity();
                Map<String, Object> map = JSON.parseObject(JSON.toJSONString(aloneGradeEquity), Map.class);
                map.forEach((k, v) -> {
                    int index = k.indexOf(":") + 1;
                    String result = k.substring(index);
                    aloneEquity.put(result, v);
                });
                String jsonString = JSON.toJSONString(aloneEquity);
                goodsEntity.setAloneGradeEquity(jsonString);
            }
        }

        if (StringUtils.isNotBlank(goodsId)) {
            goodsEntity.setGoodsId(Integer.valueOf(goodsId));
        }
        //  保存至商品数据库
        goodsService.saveOrUpdate(goodsEntity);
        return goodsEntity.getGoodsId();
    }

    // 保存商品规格信息
    @Override
    @Transactional
    public void saveGoodsSkuToDb(GoodsBaseDTO goodsBase, List<YunscSpecValueEntity> specValueList) {
        // 商品规格(10单规格 20多规格)
        Integer specType = goodsBase.getSpecType();
        // if (goodsBase.getSpecData() == null) {
        // 单规格
        if (specType == 10) {
            YunscGoodsSkuEntity skuEntity = new YunscGoodsSkuEntity();
            skuEntity.setGoodsId(goodsBase.getGoodsId());
            skuEntity.setStoreId(goodsBase.getStoreId());
            skuEntity.setGoodsPrice(goodsBase.getGoodsPrice());
            skuEntity.setLinePrice(goodsBase.getLinePrice());
            skuEntity.setStockNum(goodsBase.getStockNum());
            skuEntity.setGoodsWeight(goodsBase.getGoodsWeight());
            // 保存sku至数据库
            goodsSkuService.save(skuEntity);
            return;
        }

        // 多规格
        SpecDataDTO specData = goodsBase.getSpecData();
        List<SpecDataDTO.SkuList> skuList = specData.getSkuList();
        List<YunscGoodsSkuEntity> skuEntities = new ArrayList<>();
        skuList.forEach(sku -> {
            // 商品sku唯一标识 (由规格id组成)
            String goodsSkuId = "";
            // 规格值ID集(json格式)
            ArrayList<Object> goodsSkuValueIds = new ArrayList<>();
            // SKU的规格属性(json格式)
            List<Map<String, Map<String, Object>>> goodsSkuProps = new ArrayList<>();
            if (StringUtils.isNotEmpty(sku.getSpecValue0())) {
                YunscSpecValueEntity specValue0 = specValueList.stream()
                        .filter(s -> s.getSpecValue().equals(sku.getSpecValue0())).findFirst().orElse(null);
                if (specValue0 != null) {
                    goodsSkuId = String.valueOf(specValue0.getSpecValueId());
                    goodsSkuValueIds.add(specValue0.getSpecValueId());
                    Map<String, Map<String, Object>> props = getGoodsProps(sku.getSpecValue0(), specValue0);
                    goodsSkuProps.add(props);
                }
            }
            if (StringUtils.isNotEmpty(sku.getSpecValue1())) {
                YunscSpecValueEntity specValue1 = specValueList.stream()
                        .filter(s -> s.getSpecValue().equals(sku.getSpecValue1())).findFirst().orElse(null);
                if (specValue1 != null) {
                    goodsSkuId = goodsSkuId + "_" + specValue1.getSpecValueId();
                    goodsSkuValueIds.add(specValue1.getSpecValueId());
                    Map<String, Map<String, Object>> props = getGoodsProps(sku.getSpecValue1(), specValue1);
                    goodsSkuProps.add(props);
                }
            }
            if (StringUtils.isNotEmpty(sku.getSpecValue2())) {
                YunscSpecValueEntity specValue2 = specValueList.stream()
                        .filter(s -> s.getSpecValue().equals(sku.getSpecValue2())).findFirst().orElse(null);
                if (specValue2 != null) {
                    goodsSkuId = goodsSkuId + "_" + specValue2.getSpecValueId();
                    goodsSkuValueIds.add(specValue2.getSpecValueId());
                    Map<String, Map<String, Object>> props = getGoodsProps(sku.getSpecValue2(), specValue2);
                    goodsSkuProps.add(props);
                }
            }
            // 保存商品sku
            YunscGoodsSkuEntity skuEntity = new YunscGoodsSkuEntity();
            skuEntity.setGoodsId(goodsBase.getGoodsId());
            skuEntity.setStoreId(goodsBase.getStoreId());
            skuEntity.setGoodsSkuNo(sku.getGoodsSkuNo());
            skuEntity.setGoodsSkuId(goodsSkuId);
            skuEntity.setImageId(sku.getImageId());
            skuEntity.setGoodsPrice(String.valueOf(sku.getGoodsPrice()));
            skuEntity.setLinePrice(String.valueOf(sku.getLinePrice()));
            skuEntity.setStockNum(sku.getStockNum());
            skuEntity.setGoodsWeight(sku.getGoodsWeight());
            // SKU的规格属性(json格式)
            skuEntity.setGoodsProps(JSON.toJSONString(goodsSkuProps));
            // 规格值ID集(json格式)
            skuEntity.setSpecValueIds(JSON.toJSONString(goodsSkuValueIds));
            // 保存sku至数据库
            skuEntities.add(skuEntity);
        });
        goodsSkuService.saveBatch(skuEntities);
    }

    /**
     * 获取商品规格属性
     *
     * @param sku
     * @param specValue
     * @return
     */
    private Map<String, Map<String, Object>> getGoodsProps(String sku, YunscSpecValueEntity specValue) {
        Map<String, Map<String, Object>> map = new LinkedHashMap<>();
        HashMap<String, Object> groupMap = new HashMap<>();
        groupMap.put("name", getSpecName(specValue.getSpecId()));
        groupMap.put("id", specValue.getSpecId());
        map.put("group", groupMap);
        HashMap<String, Object> valueMap = new HashMap<>();
        valueMap.put("name", sku);
        valueMap.put("id", specValue.getSpecValueId());
        map.put("value", valueMap);
        return map;
    }

    /**
     * 根据规格ID获取规格名称
     *
     * @param specId
     * @return
     */
    private String getSpecName(Integer specId) {
        return specService.getById(specId).getSpecName();
    }

    // 保存商品属性信息，20多规格
    @Override
    @Transactional
    public List<YunscSpecValueEntity> saveGoodsSpecToDb(GoodsBaseDTO goodsBase, Integer goodsId) {
        // 商品规格(10单规格 20多规格)
        Integer specType = goodsBase.getSpecType();
        if (goodsBase.getSpecData() == null) {
            return Collections.emptyList();
        }
        // 商品属性值集合
        List<YunscSpecValueEntity> specValueList = new ArrayList<>();
        List<SpecDataDTO.SpecList> specList = goodsBase.getSpecData().getSpecList();
        List<SpecDataDTO.SkuList> skuList = goodsBase.getSpecData().getSkuList();
        if (CollectionUtils.isEmpty(specList)) {
            return Collections.emptyList();
        }
        if (CollectionUtils.isEmpty(skuList)) {
            return Collections.emptyList();
        }
        // 保存规格属性
        specList.forEach(spec -> {
            // 判断规格属性是否存在，存在不保存
            YunscSpecEntity specEntity = specService.getOne(new QueryWrapper<YunscSpecEntity>()
                    .eq("spec_name", spec.getSpecName()));
            if (specEntity == null) {
                specEntity = new YunscSpecEntity();
                specEntity.setSpecName(spec.getSpecName());
                specEntity.setStoreId(goodsBase.getStoreId());
                // 不存在则保存
                specService.save(specEntity);
            }
            // 保存规格值
            YunscSpecEntity finalSpecEntity = specEntity;
            List<SpecDataDTO.SpecList.ValueList> valueList = spec.getValueList();
            valueList.forEach(value -> {
                // 判断规格值是否存在，存在不保存
                YunscSpecValueEntity specValueEntity = specValueService.getOne(new QueryWrapper<YunscSpecValueEntity>()
                        .eq("spec_value", value.getSpecValue()));
                if (specValueEntity == null) {
                    specValueEntity = new YunscSpecValueEntity();
                    specValueEntity.setSpecId(finalSpecEntity.getSpecId());
                    specValueEntity.setSpecValue(value.getSpecValue());
                    specValueEntity.setStoreId(finalSpecEntity.getStoreId());
                    // 保存商品规格值表
                    specValueService.save(specValueEntity);
                }
                // 保存规格值集合
                specValueList.add(specValueEntity);
                // 保存商品规格值关系表
                YunscGoodsSpecRelEntity goodsSpecRel = new YunscGoodsSpecRelEntity();
                goodsSpecRel.setSpecId(finalSpecEntity.getSpecId());
                goodsSpecRel.setSpecValueId(specValueEntity.getSpecValueId());
                goodsSpecRel.setGoodsId(goodsId);
                goodsSpecRel.setStoreId(finalSpecEntity.getStoreId());
                // 保存商品规格值关系表
                goodsSpecRelService.save(goodsSpecRel);
            });
        });
        return specValueList;
    }

    // 保存商品与分类关系记录表
    @Override
    @Transactional
    public void saveGoodsCategoryToDb(List<Integer> categoryIds, Integer goodsId, Integer storeId) {
        List<YunscGoodsCategoryRelEntity> goodsCategoryRelEntities = categoryIds.stream().map(categoryId -> {
            YunscGoodsCategoryRelEntity goodsCategoryRel = new YunscGoodsCategoryRelEntity();
            goodsCategoryRel.setGoodsId(goodsId);
            goodsCategoryRel.setCategoryId(categoryId);
            goodsCategoryRel.setStoreId(storeId);
            return goodsCategoryRel;
        }).collect(Collectors.toList());
        goodsCategoryRelService.saveBatch(goodsCategoryRelEntities);
    }

    // 保存商品图片
    @Override
    @Transactional
    public void saveGoodsImageToDb(List<Integer> imageIds, Integer goodsId, Integer storeId) {
        imageIds.forEach(imageId -> {
            YunscGoodsImageEntity goodsImageRel = new YunscGoodsImageEntity();
            goodsImageRel.setGoodsId(goodsId);
            goodsImageRel.setImageId(imageId);
            goodsImageRel.setStoreId(storeId);
            goodsImageService.save(goodsImageRel);
        });
        /*List<YunscGoodsImageEntity> goodsImageRelEntities = imageIds.stream().map(imageId -> {
            YunscGoodsImageEntity goodsImageRel = new YunscGoodsImageEntity();
            goodsImageRel.setGoodsId(goodsId);
            goodsImageRel.setImageId(imageId);
            goodsImageRel.setStoreId(storeId);
            return goodsImageRel;
        }).collect(Collectors.toList());
        goodsImageService.saveBatch(goodsImageRelEntities);*/
    }

    // 保存商品服务
    @Override
    @Transactional
    public void saveGoodsServiceToDb(List<Integer> serviceIds, Integer goodsId, Integer storeId) {
        List<YunscGoodsServiceRelEntity> goodsServiceRelEntities = serviceIds.stream().map(serviceId -> {
            YunscGoodsServiceRelEntity goodsServiceRel = new YunscGoodsServiceRelEntity();
            goodsServiceRel.setGoodsId(goodsId);
            goodsServiceRel.setServiceId(serviceId);
            goodsServiceRel.setStoreId(storeId);
            return goodsServiceRel;
        }).collect(Collectors.toList());
        goodsServiceRelService.saveBatch(goodsServiceRelEntities);
    }

    // 编辑商品信息
    @Override
    @Transactional
    public void editGoodsInfo(GoodsParamsDTO goodsParams, Integer storeId) {
        // 1、修改商品基本信息
        GoodsBaseDTO goodsBase = goodsParams.getForm();
        // 设置门店id
        goodsBase.setStoreId(storeId);
        goodsBase.setGoodsId(Integer.valueOf(goodsParams.getGoodsId()));
        // 修改商品基本信息
        goodsService.saveGoodsToDb(goodsBase, goodsParams.getGoodsId());
        // 2、修改商品规格信息
        List<YunscSpecValueEntity> specValueList = goodsService.editGoodsToSpec(goodsBase, goodsParams.getGoodsId());
        // 3、修改商品sku到表goods_sku
        goodsService.editGoodsToSku(goodsBase, specValueList, goodsParams.getGoodsId());
        // 4、修改商品与分类关系记录表
        goodsService.editGoodsToCategory(goodsBase.getCategoryIds(), goodsParams.getGoodsId(), storeId);
        // 5、修改商品与图片关系记录表
        goodsService.editGoodsToImage(goodsBase.getImagesIds(), goodsParams.getGoodsId(), storeId);
        // 6、修改商品与服务记录表
        goodsService.editGoodsToService(goodsBase.getServiceIds(), goodsParams.getGoodsId(), storeId);

    }

    // 编辑商品规格信息
    @Override
    @Transactional
    public List<YunscSpecValueEntity> editGoodsToSpec(GoodsBaseDTO goodsBase, String goodsId) {
        // 删除原来商品规格信息
        goodsSpecRelService.remove(new QueryWrapper<YunscGoodsSpecRelEntity>().eq("goods_id", goodsId));
        // 添加新的商品规格信息
        return goodsService.saveGoodsSpecToDb(goodsBase, Integer.valueOf(goodsId));
    }

    @Override
    @Transactional
    public void editGoodsToSku(GoodsBaseDTO goodsBase, List<YunscSpecValueEntity> specValueList, String goodsId) {
        // 删除原来商品sku信息
        goodsSkuService.remove(new QueryWrapper<YunscGoodsSkuEntity>().eq("goods_id", goodsId));
        // 添加新的商品规格信息
        goodsService.saveGoodsSkuToDb(goodsBase, specValueList);

    }

    @Override
    @Transactional
    public void editGoodsToCategory(List<Integer> categoryIds, String goodsId, Integer storeId) {
        // 删除原来商品与分类关系记录表
        goodsCategoryRelService.remove(new QueryWrapper<YunscGoodsCategoryRelEntity>().eq("goods_id", goodsId));

        // 添加新的商品与分类关系
        goodsService.saveGoodsCategoryToDb(categoryIds, Integer.valueOf(goodsId), storeId);
    }
    /*@Override
    @Transactional
    public void editGoodsToCategory(List<Integer> categoryIds, String goodsId, Integer storeId) {
        // 查询现有的商品与分类关系
        List<YunscGoodsCategoryRelEntity> existingRelations = goodsCategoryRelService
                .list(new QueryWrapper<YunscGoodsCategoryRelEntity>().eq("goods_id", goodsId));

        // 存储待删除的分类ID
        List<Integer> toDeleteCategoryIds = new ArrayList<>();

        for (YunscGoodsCategoryRelEntity entity : existingRelations) {
            if (!categoryIds.contains(entity.getCategoryId())) {
                // 如果不在新分类中，标记为待删除
                toDeleteCategoryIds.add(entity.getId());
            } else {
                categoryIds.remove(entity.getCategoryId());
            }
        }

        // 删除不再关联的分类
        goodsCategoryRelService.removeByIds(toDeleteCategoryIds);

        // 添加新的商品与分类关系
        goodsService.saveGoodsCategoryToDb(categoryIds, Integer.valueOf(goodsId), storeId);
    }*/

    @Override
    public void editGoodsToImage(List<Integer> imageIds, String goodsId, Integer storeId) {
        /*// 查询现有的商品与图片关系
        List<YunscGoodsImageEntity> existingRelations = goodsImageService
                .list(new QueryWrapper<YunscGoodsImageEntity>().eq("goods_id", goodsId));
        // 存储待删除的图片ID
        List<Integer> toDeleteImageIds = new ArrayList<>();
        for (YunscGoodsImageEntity entity : existingRelations) {
            if (!imageIds.contains(entity.getImageId())) {
                // 如果不在新图片中，标记为待删除
                toDeleteImageIds.add(entity.getId());
            } else {
                imageIds.remove(entity.getImageId());
            }
        }
        // 删除不再关联的图片
        goodsImageService.removeByIds(toDeleteImageIds);*/
        // 先删除原来商品图片信息
        goodsImageService.remove(new QueryWrapper<YunscGoodsImageEntity>().eq("goods_id", goodsId));

        // 添加新的商品与图片关系
        goodsService.saveGoodsImageToDb(imageIds, Integer.valueOf(goodsId), storeId);

    }

    @Override
    @Transactional
    public void editGoodsToService(List<Integer> serviceIds, String goodsId, Integer storeId) {
        // 删除原来商品服务信息
        goodsServiceRelService.remove(new QueryWrapper<YunscGoodsServiceRelEntity>().eq("goods_id", goodsId));

        // 添加新的商品与服务关系
        goodsService.saveGoodsServiceToDb(serviceIds, Integer.valueOf(goodsId), storeId);
    }

    // 删除商品信息
    @Override
    @Transactional
    public void deleteGoodsByIds(List<Integer> goodsIds) {
        /* // 1.删除商品基本信息
        goodsService.removeByIds(goodsIds);
        // 2.删除商品关联的规格信息
        goodsSpecRelService.remove(new QueryWrapper<YunscGoodsSpecRelEntity>().in("goods_id", goodsIds));
        // 3.删除商品关联的sku信息
        goodsSkuService.remove(new QueryWrapper<YunscGoodsSkuEntity>().in("goods_id", goodsIds));
        // 4.删除商品关联的分类信息
        goodsCategoryRelService.remove(new QueryWrapper<YunscGoodsCategoryRelEntity>().in("goods_id", goodsIds));
        // 5.删除商品关联的图片信息
        goodsImageService.remove(new QueryWrapper<YunscGoodsImageEntity>().in("goods_id", goodsIds));
        // 6.删除商品关联的服务信息
        goodsServiceRelService.remove(new QueryWrapper<YunscGoodsServiceRelEntity>().in("goods_id", goodsIds)); */
        // 修改商品基本信息is_delete字段为1
        goodsService.update(new UpdateWrapper<YunscGoodsEntity>().in("goods_id", goodsIds).set("is_delete", 1));
    }

    // 编辑商品状态
    @Override
    @Transactional
    public void editGoodsState(List<Integer> goodsIds, boolean state) {
        // 根据id修改商品状态
        goodsIds.forEach(goodsId -> {
            // 如果state为true，则修改为上架，否则修改为下架
            if (state) {
                // 商品上架
                boolean flag = goodsService.update(new UpdateWrapper<YunscGoodsEntity>()
                        .eq("goods_id", goodsId).set("status", 10));
                if (!flag) {
                    throw new YunscException(BizCodeEnum.PRODUCT_UP_EXCEPTION.getMsg(), BizCodeEnum.PRODUCT_UP_EXCEPTION.getCode());
                }
            } else {
                // 商品下架
                boolean flag = goodsService.update(new UpdateWrapper<YunscGoodsEntity>()
                        .eq("goods_id", goodsId).set("status", 20));
                if (!flag) {
                    throw new YunscException(BizCodeEnum.PRODUCT_DOWN_EXCEPTION.getMsg(), BizCodeEnum.PRODUCT_DOWN_EXCEPTION.getCode());
                }
            }
        });
    }

    @Override
    public List<GoodsDetailVO> queryGoodsByCategoryId(Integer categoryId, Integer showNum, String goodsSort) {
        List<GoodsDetailVO> goodsEntities = this.baseMapper.selectGoodsByCategoryId(categoryId, showNum, goodsSort);
        goodsEntities.forEach(goods -> {
            goods.setGoodsImage(queryGoodsDefaultImageUrl(goods.getGoodsId()));
        });
        return goodsEntities;
    }

    @Override
    public List<GoodsDetailVO> queryGoodsByIds(List<Integer> goodsIds) {
        List<YunscGoodsEntity> goodsEntities = this.listByIds(goodsIds);
        if (CollectionUtils.isEmpty(goodsEntities)) {
            return Collections.emptyList();
        }
        return goodsEntities.stream().map(goods -> {
            GoodsDetailVO goodsDetailVO = new GoodsDetailVO();
            goodsDetailVO.setGoodsId(goods.getGoodsId());
            goodsDetailVO.setGoodsName(goods.getGoodsName());
            String imageUrl = queryGoodsDefaultImageUrl(goods.getGoodsId());
            goodsDetailVO.setGoodsImage(imageUrl);
            goodsDetailVO.setGoodsPriceMin(goods.getGoodsPriceMin());
            goodsDetailVO.setLinePriceMin(goods.getLinePriceMin());
            goodsDetailVO.setSellingPoint(goods.getSellingPoint());
            goodsDetailVO.setGoodsSales(goods.getSalesInitial() + goods.getSalesActual());
            return goodsDetailVO;
        }).collect(Collectors.toList());

    }

    @Override
    public GoodsDetailVO queryGoodsSpecData(Integer goodsId) {
        GoodsBaseDTO goods = this.baseMapper.selectGoodsBaseById(goodsId);
        if (goods == null) {
            return null;
        }
        GoodsDetailVO goodsDetail = new GoodsDetailVO();
        // BeanUtils.copyProperties(goods, goodsDetail);
        // 商品规格
        List<SpecListDTO> specList = goodsSpecRelService.querySpecListById(goodsId);
        goodsDetail.setSpecList(specList);

        // 商品sku
        goodsDetail.setSkuList(goodsSkuService.querySkuListByGoodsId(goodsId));

        return goodsDetail;

    }

    @Override
    public GoodsInfoVO queryGoodsInfo(Integer goodsId, String goodsSkuId) {

        YunscGoodsEntity goods = this.getById(goodsId);
        if (goods == null) {
            throw new YunscException("商品不存在");
        }
        GoodsInfoVO goodsInfo = new GoodsInfoVO();
        BeanUtils.copyProperties(goods, goodsInfo);
        // 获取商品sku信息
        YunscGoodsSkuEntity goodsSku = goodsSkuService.getOne(new QueryWrapper<YunscGoodsSkuEntity>()
                .eq("goods_sku_id", goodsSkuId)
                .eq("goods_id", goodsId));
        if (goodsSku == null) {
            return goodsInfo;
        }
        // 解析商品规格属性
        GoodsSkuDTO goodsSkuDto = new GoodsSkuDTO();
        BeanUtils.copyProperties(goodsSku, goodsSkuDto);
        Object goodsProps = goodsSku.getGoodsProps();
        if (goodsProps != null) {
            List<Map<String, Object>> goodsPropsList = JSON.parseObject(goodsProps.toString(), List.class);
            goodsSkuDto.setGoodsProps(goodsPropsList);
        }
        // 商品图片
        Integer imageId = goodsSku.getImageId();
        if (imageId == null || imageId == 0){
            goodsInfo.setGoodsImage(this.queryGoodsDefaultImageUrl(goodsId));
        }else {
            goodsInfo.setGoodsImage(uploadFileService.queryFileUrlById(imageId));
        }
        goodsInfo.setSkuInfo(goodsSkuDto);
        goodsInfo.setGoodsSales(goods.getSalesInitial() + goods.getSalesActual());
        goodsInfo.setContent(null);
        return goodsInfo;
    }

    @Override
    @Transactional
    public void deductStock(Integer goodsId, String goodsSkuId, Integer stockNum) {
        // 更新商品sku库存
        int updated = goodsSkuService.editGoodsSkuStockNum(goodsId, goodsSkuId, stockNum);
        if (updated == 0) {
            throw new YunscException("商品库存扣减失败");
        }
        // 更新商品库存
        int stockNumInDb = this.baseMapper.updateGoodsStockNum(goodsId, stockNum);
        if (stockNumInDb == 0) {
            throw new YunscException("商品库存扣减失败");
        }
    }

    @Override
    @Transactional
    public void addGoodsStock(Integer goodsId, String goodsSkuId, Integer totalNum) {
        // 1.更新商品sku库存
        goodsSkuService.addGoodsSkuStockNum(goodsId, goodsSkuId, totalNum);

        // 2.更新商品总库存
        this.baseMapper.addGoodsStockNum(goodsId, totalNum);

    }

    @Override
    public int queryGoodsTotalCount(int startInSeconds, int endInSeconds, Integer storeId) {
        LambdaQueryWrapper<YunscGoodsEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YunscGoodsEntity::getStoreId, storeId);
        lqw.eq(YunscGoodsEntity::getIsDelete, 0);
        if (startInSeconds > 0 && endInSeconds > 0){
            lqw.between(YunscGoodsEntity::getCreateTime, startInSeconds, endInSeconds);
        }
        return this.count(lqw);
    }

    @Override
    public int querySoldOutGoodsTotal(Integer storeId) {
        return this.count(new QueryWrapper<YunscGoodsEntity>()
               .eq("store_id", storeId)
               .eq("stock_total", 0)
                .eq("is_delete", 0));
    }

    @Override
    public List<GoodsInfoVO> queryGoodsListByIds(String goodsIds, Integer currentStoreId) {
        List<Integer> goodsIdList = Arrays.stream(goodsIds.split(",")).map(Integer::parseInt).collect(Collectors.toList());
        List<YunscGoodsEntity> goodsEntities = this.list(new QueryWrapper<YunscGoodsEntity>()
               .eq("store_id", currentStoreId)
               .eq("is_delete", 0)
               .in("goods_id", goodsIdList));
        if (CollectionUtils.isEmpty(goodsEntities)) {
            return Collections.emptyList();
        }
        List<GoodsInfoVO> goodsInfoVOList = goodsEntities.stream().map(goods -> {
            GoodsInfoVO goodsInfoVO = new GoodsInfoVO();
            BeanUtils.copyProperties(goods, goodsInfoVO);
            goodsInfoVO.setGoodsImage(this.queryGoodsDefaultImageUrl(goods.getGoodsId()));
            return goodsInfoVO;
        }).collect(Collectors.toList());
        return goodsInfoVOList;

    }


}